<template>
  <div class="ip-location-test">
    <div class="page-header">
      <h2>IP定位问题诊断</h2>
      <p>诊断和修复IP定位返回空城市的问题</p>
    </div>

    <!-- 当前IP信息 -->
    <el-card class="ip-info-card">
      <template #header>
        <h3>当前IP信息</h3>
      </template>
      
      <div class="ip-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="检测到的IP">{{ detectedIP || '检测中...' }}</el-descriptions-item>
          <el-descriptions-item label="IP类型">{{ ipType }}</el-descriptions-item>
          <el-descriptions-item label="是否本地IP">{{ isLocalIP ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="建议处理">{{ suggestion }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <!-- IP定位测试 -->
    <el-card class="test-card">
      <template #header>
        <h3>IP定位测试</h3>
      </template>

      <div class="test-section">
        <el-button 
          type="primary" 
          @click="testCurrentIP"
          :loading="testing"
        >
          测试当前IP定位
        </el-button>
        
        <el-button 
          type="success" 
          @click="testPublicIP"
          :loading="testingPublic"
        >
          测试公网IP定位
        </el-button>
        
        <el-button 
          type="warning" 
          @click="testLocalIP"
          :loading="testingLocal"
        >
          测试本地IP处理
        </el-button>
      </div>

      <!-- 测试结果 -->
      <div v-if="testResults.length > 0" class="test-results">
        <h4>测试结果：</h4>
        <div v-for="(result, index) in testResults" :key="index" class="result-item">
          <el-card :class="['result-card', result.success ? 'success' : 'error']">
            <template #header>
              <div class="result-header">
                <span>{{ result.title }}</span>
                <el-tag :type="result.success ? 'success' : 'danger'">
                  {{ result.success ? '成功' : '失败' }}
                </el-tag>
              </div>
            </template>
            
            <div class="result-content">
              <div v-if="result.data" class="location-data">
                <el-descriptions :column="2" size="small">
                  <el-descriptions-item label="城市">{{ result.data.city || '空' }}</el-descriptions-item>
                  <el-descriptions-item label="省份">{{ result.data.province || '空' }}</el-descriptions-item>
                  <el-descriptions-item label="地址">{{ result.data.address || '空' }}</el-descriptions-item>
                  <el-descriptions-item label="数据源">{{ result.data.source || '未知' }}</el-descriptions-item>
                  <el-descriptions-item label="坐标">
                    {{ result.data.latitude }}, {{ result.data.longitude }}
                  </el-descriptions-item>
                  <el-descriptions-item label="IP">{{ result.data.ip || '未知' }}</el-descriptions-item>
                </el-descriptions>
              </div>
              
              <div v-if="result.error" class="error-info">
                <el-alert
                  :title="result.error"
                  type="error"
                  show-icon
                  :closable="false"
                />
              </div>
              
              <!-- 原始数据 -->
              <el-collapse style="margin-top: 12px;">
                <el-collapse-item title="查看原始数据" name="raw">
                  <pre>{{ JSON.stringify(result.raw, null, 2) }}</pre>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 解决方案 -->
    <el-card class="solution-card">
      <template #header>
        <h3>问题解决方案</h3>
      </template>

      <div class="solutions">
        <el-alert
          title="本地IP问题"
          description="如果检测到本地IP（127.0.0.1），系统会自动使用默认位置（北京）"
          type="info"
          show-icon
          :closable="false"
        />
        
        <el-alert
          title="高德API返回空数据"
          description="如果高德IP定位返回空的城市数组，系统会自动降级到免费IP定位服务"
          type="warning"
          show-icon
          :closable="false"
        />
        
        <el-alert
          title="生产环境建议"
          description="在生产环境中，确保服务器能获取到真实的客户端IP地址，而不是代理或负载均衡器的IP"
          type="success"
          show-icon
          :closable="false"
        />
      </div>
    </el-card>

    <!-- 调试信息 -->
    <el-card class="debug-card">
      <template #header>
        <h3>调试信息</h3>
      </template>

      <div class="debug-info">
        <h4>浏览器检测到的信息：</h4>
        <ul>
          <li>User Agent: {{ navigator.userAgent }}</li>
          <li>语言: {{ navigator.language }}</li>
          <li>时区: {{ Intl.DateTimeFormat().resolvedOptions().timeZone }}</li>
          <li>屏幕分辨率: {{ screen.width }}x{{ screen.height }}</li>
        </ul>
        
        <h4>网络信息：</h4>
        <ul>
          <li>连接类型: {{ networkInfo.effectiveType || '未知' }}</li>
          <li>下行速度: {{ networkInfo.downlink || '未知' }}Mbps</li>
          <li>RTT: {{ networkInfo.rtt || '未知' }}ms</li>
        </ul>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { locationAPI } from '@/api'

const detectedIP = ref('')
const testing = ref(false)
const testingPublic = ref(false)
const testingLocal = ref(false)
const testResults = ref([])

// 计算属性
const isLocalIP = computed(() => {
  if (!detectedIP.value) return false
  
  const localIPs = ['127.0.0.1', 'localhost', '::1', '0.0.0.0']
  if (localIPs.includes(detectedIP.value)) return true
  
  const privateRanges = [
    /^10\./,
    /^172\.(1[6-9]|2[0-9]|3[0-1])\./,
    /^192\.168\./,
    /^169\.254\./
  ]
  
  return privateRanges.some(range => range.test(detectedIP.value))
})

const ipType = computed(() => {
  if (!detectedIP.value) return '未知'
  if (detectedIP.value === '127.0.0.1' || detectedIP.value === 'localhost') return '本地回环'
  if (isLocalIP.value) return '内网IP'
  return '公网IP'
})

const suggestion = computed(() => {
  if (isLocalIP.value) return '使用默认位置'
  return '可以进行IP定位'
})

const networkInfo = computed(() => {
  return navigator.connection || navigator.mozConnection || navigator.webkitConnection || {}
})

// 方法
const detectIP = async () => {
  try {
    // 尝试通过API获取IP
    const response = await fetch('/api/v1/location/ip')
    const result = await response.json()
    if (result.code === 200 && result.data.ip) {
      detectedIP.value = result.data.ip
    }
  } catch (error) {
    console.error('获取IP失败:', error)
    detectedIP.value = '无法检测'
  }
}

const testCurrentIP = async () => {
  testing.value = true
  try {
    const response = await locationAPI.getLocationByIP()
    
    testResults.value.unshift({
      title: '当前IP定位测试',
      success: response.data.city && response.data.city !== '未知城市',
      data: response.data,
      raw: response,
      timestamp: new Date().toLocaleString()
    })
    
    if (response.data.city && response.data.city !== '未知城市') {
      ElMessage.success('当前IP定位成功')
    } else {
      ElMessage.warning('当前IP定位返回空城市')
    }
  } catch (error) {
    testResults.value.unshift({
      title: '当前IP定位测试',
      success: false,
      error: error.message,
      raw: error,
      timestamp: new Date().toLocaleString()
    })
    ElMessage.error('当前IP定位失败')
  } finally {
    testing.value = false
  }
}

const testPublicIP = async () => {
  testingPublic.value = true
  try {
    // 使用一个已知的公网IP进行测试
    const publicIP = '8.8.8.8' // Google DNS
    const response = await locationAPI.getLocationByIP(publicIP)
    
    testResults.value.unshift({
      title: `公网IP定位测试 (${publicIP})`,
      success: response.data.city && response.data.city !== '未知城市',
      data: response.data,
      raw: response,
      timestamp: new Date().toLocaleString()
    })
    
    ElMessage.success('公网IP定位测试完成')
  } catch (error) {
    testResults.value.unshift({
      title: '公网IP定位测试',
      success: false,
      error: error.message,
      raw: error,
      timestamp: new Date().toLocaleString()
    })
    ElMessage.error('公网IP定位测试失败')
  } finally {
    testingPublic.value = false
  }
}

const testLocalIP = async () => {
  testingLocal.value = true
  try {
    // 测试本地IP处理
    const localIP = '127.0.0.1'
    const response = await locationAPI.getLocationByIP(localIP)
    
    testResults.value.unshift({
      title: `本地IP处理测试 (${localIP})`,
      success: response.data.source === 'default',
      data: response.data,
      raw: response,
      timestamp: new Date().toLocaleString()
    })
    
    if (response.data.source === 'default') {
      ElMessage.success('本地IP正确处理为默认位置')
    } else {
      ElMessage.warning('本地IP处理可能有问题')
    }
  } catch (error) {
    testResults.value.unshift({
      title: '本地IP处理测试',
      success: false,
      error: error.message,
      raw: error,
      timestamp: new Date().toLocaleString()
    })
    ElMessage.error('本地IP处理测试失败')
  } finally {
    testingLocal.value = false
  }
}

// 生命周期
onMounted(() => {
  detectIP()
})
</script>

<style scoped>
.ip-location-test {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #409eff;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  margin: 0;
}

.ip-info-card,
.test-card,
.solution-card,
.debug-card {
  margin-bottom: 20px;
}

.test-section {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.test-results {
  margin-top: 20px;
}

.result-item {
  margin-bottom: 16px;
}

.result-card {
  border-left: 4px solid #e4e7ed;
}

.result-card.success {
  border-left-color: #67c23a;
}

.result-card.error {
  border-left-color: #f56c6c;
}

.result-header {
  display: flex;
  justify-content: between;
  align-items: center;
}

.solutions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.debug-info h4 {
  margin: 16px 0 8px 0;
  color: #303133;
}

.debug-info ul {
  margin: 0;
  padding-left: 20px;
}

.debug-info li {
  margin-bottom: 4px;
  font-size: 14px;
  color: #606266;
}

pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  overflow-x: auto;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ip-location-test {
    padding: 16px;
  }
  
  .test-section {
    flex-direction: column;
  }
}
</style>
